Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
题目大意:判断一个给定链表是否存在环
题目难度:Easy
/**
* Created by gzdaijie on 16/6/17
* 两个指针从头开始走,一个一次走一步,另一个一次走2步,如果存在环,必定会相遇
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) return false;
ListNode faster = head.next;
while (faster.next != null && faster.next.next != null) {
if (head == faster) return true;
head = head.next;
faster = faster.next.next;
}
return false;
}
}